package com.qmx.qmxapp.base;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.koushikdutta.async.AsyncServer;
import com.koushikdutta.async.AsyncSocket;
import com.koushikdutta.async.ByteBufferList;
import com.koushikdutta.async.DataEmitter;
import com.koushikdutta.async.Util;
import com.koushikdutta.async.callback.CompletedCallback;
import com.koushikdutta.async.callback.ConnectCallback;
import com.koushikdutta.async.callback.DataCallback;
import com.koushikdutta.async.callback.WritableCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.qmx.qmxapp.R;
import com.qmx.qmxapp.bean.ConfigInfo;
import com.qmx.qmxapp.bean.ContactModel;
import com.qmx.qmxapp.bean.LzyResponse;
import com.qmx.qmxapp.bean.MessageObservable;
import com.qmx.qmxapp.bean.TokenListModel;
import com.qmx.qmxapp.callback.JsonCallback;
import com.qmx.qmxapp.constant.AppConstant;
import com.qmx.qmxapp.constant.ComParamContact;
import com.qmx.qmxapp.data.SectionMultipleItem;
import com.qmx.qmxapp.data.Video;
import com.qmx.qmxapp.realm.Token;
import com.qmx.qmxapp.realm.TokenList;
import com.qmx.qmxapp.token.TokenManager;
import com.qmx.qmxapp.utils.SocketUtil;
import com.qmx.qmxapp.utils.StringUtils;
import com.qmx.qmxapp.view.DlgMgr;
import com.tencent.TIMManager;
import com.tencent.av.sdk.AVContext;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.adapter.CommonConstants;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomConfig;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.listener.ILiveEventHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Unbinder;
import io.realm.Realm;
import io.realm.RealmList;
import me.jessyan.autosize.internal.CustomAdapt;

import static com.qmx.qmxapp.activity.CreateActivity.REQ_PERMISSION_CODE;

/**
 * @author chengxiangtong
 * @date 2018/10/8
 */
public class BaseActivity extends AppCompatActivity implements CustomAdapt {
    private Unbinder unbinder;
    public SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    private Gson mGson = new Gson();
    private Realm realm;
    public String __TOKEN__ = "";
    private List<TokenList> lists;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        unbinder = ButterKnife.bind(this);
        sharedPreferences = getSharedPreferences(BaseApplication.getInstance().getPackageName(), Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        Log.i("TokenManager", TokenManager.getInstance().getAuthModel().getToken());
        //        Log.i("CLIENT_ID", sharedPreferences.getString(AppConstant.CLIENT_ID, "111111111111111111"));
    }

    @Override
    public boolean isBaseOnWidth() {
        return false;
    }

    @Override
    public float getSizeInDp() {
        return 0;
    }


    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }


    public void token(Realm mRealm) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                TokenList list = realm.where(TokenList.class).findFirst();
                if (list != null) {
                    __TOKEN__ = list.getToken();
                    list.deleteFromRealm();
                }
                Log.i("token", __TOKEN__ + "--------" + (mRealm.where(TokenList.class).findAll()).size());
            }
        });
    }

    public void getHttpToken() {
        realm = Realm.getDefaultInstance();
        lists = realm.where(TokenList.class).findAll();
        if (!lists.isEmpty() && lists.size() != 0) {
            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.deleteAll();
                }
            });
        }
        OkGo.<LzyResponse<TokenListModel>>post(AppConstant.Url + ComParamContact.tokenFrom.PATH)
                .headers(ComParamContact.tokenFrom.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .execute(new JsonCallback<LzyResponse<TokenListModel>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<TokenListModel>> response) {
                        String json = mGson.toJson(response.body().data);
                        final TokenListModel contactModel = mGson.fromJson(json, TokenListModel.class);
                        Log.i("TokenListModel", contactModel.get__token__() + "");

                        realm.executeTransactionAsync(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                for (String s : contactModel.get__token__()) {
                                    TokenList tokenList = realm.createObject(TokenList.class);
                                    tokenList.setToken(s);
                                }
                            }
                        });
                        lists = realm.where(TokenList.class).findAll();
                        Log.i("TokenList", lists.size() + "");

                    }

                    @Override
                    public void onError(Response<LzyResponse<TokenListModel>> response) {
                        Log.e("TokenListModelonError ", response.toString());
                        //                            handleError(response);
                    }
                });

    }

    public void saveClientId(JSONObject jsonObject) {
        try {
            if (!jsonObject.opt("code").equals(911)) {
                String str = new JSONObject(jsonObject.opt("data").toString()).opt("client_id").toString();
                Log.i("CLIENT_ID===", str);
                editor.putString(AppConstant.CLIENT_ID, str);
                editor.commit();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //    public void getClientId() {
    //
    //        AsyncServer.getDefault().connectSocket(AppConstant.HOSTNAME, AppConstant.PORT, new ConnectCallback() {
    //            @Override
    //            public void onConnectCompleted(Exception ex, final AsyncSocket socket) {
    //                if (ex != null) {
    //                    Log.d("getClientId", "连接出错");
    //                    return;
    //                }
    //                socket.setDataCallback(new DataCallback() {
    //                    @Override
    //                    public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
    //                        try {
    //                            JSONObject jsonObject = StringUtils.getDataHexString(bb);
    //                            if (!jsonObject.opt("code").equals(911)) {
    //                                String str = new JSONObject(jsonObject.opt("data").toString()).opt("client_id").toString();
    //                                Log.i("CLIENT_ID===", str);
    //                                editor.putString(AppConstant.CLIENT_ID, str);
    //                                editor.commit();
    //                            }
    //                        } catch (JSONException e) {
    //                            e.printStackTrace();
    //                        }
    //                    }
    //                });
    //                socket.setClosedCallback(new CompletedCallback() {
    //                    @Override
    //                    public void onCompleted(Exception ex) {
    //                        if (ex != null) {
    //                            Log.d("getClientId", "setClosedCallback出错");
    //                            return;
    //                        }
    //                        Log.d("getClientId", "setClosedCallback");
    //                    }
    //                });
    //                socket.setEndCallback(new CompletedCallback() {
    //                    @Override
    //                    public void onCompleted(Exception ex) {
    //                        if (ex != null) {
    //                            Log.d("getClientId", "setEndCallback出错");
    //                            return;
    //                        }
    //                        Log.d("getClientId", "setEndCallback");
    //                    }
    //                });
    //                socket.setWriteableCallback(new WritableCallback() {
    //                    @Override
    //                    public void onWriteable() {
    //                        Log.d("PushService", "WritableCallback");
    //                    }
    //                });
    //                final HashMap hashMap = new HashMap();
    //                hashMap.put("token", TokenManager.getInstance().getAuthModel().getToken());
    //                Util.writeAll(socket, StringUtils.socketData("auth@login", hashMap).getBytes(), new CompletedCallback() {
    //                    @Override
    //                    public void onCompleted(Exception ex) {
    //                        if (ex != null) {
    //                            Log.d("getClientId", "writeAll出错");
    //                            return;
    //                        }
    //                        hashMap.clear();
    //                        //                        Log.d("writeAll", socketData().getBytes() + "");
    //                    }
    //                });
    //            }
    //        });
    //    }

    public void getVariableToken() {
        AsyncServer.getDefault().connectSocket(AppConstant.HOSTNAME, AppConstant.PORT, new ConnectCallback() {
            @Override
            public void onConnectCompleted(Exception ex, final AsyncSocket socket) {
                if (ex != null) {
                    Log.d("getVariableToken", "连接出错");
                    return;
                }
                socket.setDataCallback(new DataCallback() {
                    @Override
                    public void onDataAvailable(DataEmitter emitter, ByteBufferList bb) {
                        try {
                            JSONObject jsonObject = StringUtils.getDataHexString(bb);
                            if (!jsonObject.opt("code").equals(911)) {
                                String str = new JSONObject(jsonObject.opt("data").toString()).opt("token").toString();
                                Log.i("getVariableToken", str);
                                editor.putString(AppConstant.__TOKEN__, str);
                                editor.commit();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                socket.setClosedCallback(new CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        if (ex != null) {
                            Log.d("getVariableToken", "setClosedCallback出错");
                            return;
                        }
                        Log.d("getVariableToken", "setClosedCallback");
                    }
                });
                socket.setEndCallback(new CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        if (ex != null) {
                            Log.d("getVariableToken", "setEndCallback" + ex.getCause());
                            return;
                        }
                        Log.d("getVariableToken", "setEndCallback");
                    }
                });
                socket.setWriteableCallback(new WritableCallback() {
                    @Override
                    public void onWriteable() {
                        Log.d("getVariableToken", "WritableCallback");
                    }
                });
                //                final HashMap hashMap = new HashMap();
                //                hashMap.put("token", TokenManager.getInstance().getAuthModel().getToken());
                Util.writeAll(socket, StringUtils.socketData("auth@token", null).getBytes(), new CompletedCallback() {
                    @Override
                    public void onCompleted(Exception ex) {
                        if (ex != null) {
                            Log.d("getVariableToken", "writeAll出错");
                            return;
                        }
                        //                        hashMap.clear();
                        //                        Log.d("writeAll", socketData().getBytes() + "");
                    }
                });
            }
        });
    }

    /**
     * 初始化并登录TRTC SDK
     */
    public void afterUserSelected(String userId) {
        // Step 1: 初始化TRTC SDK
        initTrtcSDK(ConfigInfo.getInstance().getSdkAppId());
        // Step 2: 登录TRTC SDK
        loginTrtcSDK(userId, sharedPreferences.getString(AppConstant.USER_SIG, ""));
        Log.e("userId =========", userId);
        Log.e("userId", sharedPreferences.getString(AppConstant.USER_SIG, ""));
        //                loginTrtcSDK(userId, ConfigInfo.getInstance().getUserMap().get(userId));
    }

    /**
     * 初始化TRTC SDK
     */
    private void initTrtcSDK(int sdkAppId) {
        // 初始化ILiveSDK
        ILiveSDK.getInstance().initSdk(BaseActivity.this, sdkAppId, 0);
        // 初始化房间模块
        ILiveRoomManager.getInstance().init(new ILiveRoomConfig()
                .setRoomMsgListener(MessageObservable.getInstance()));
        //        Log.e("ILiveSDK ", ILiveSDK.getInstance().getVersion());
        //        Log.e("AVSDK  ", AVContext.sdkVersion);
        //        Log.e("IMSDK  ", TIMManager.getInstance().getVersion());
        ILiveSDK.getInstance().setChannelMode(CommonConstants.E_ChannelMode.E_ChannelIMSDK);
    }

    /**
     * 登录TRTC SDK
     */
    private void loginTrtcSDK(String useId, String userSig) {
        // 添加事件监听
        ILiveSDK.getInstance().addEventHandler(new ILiveEventHandler() {
            // 登录成功事件
            @Override
            public void onLoginSuccess(String userId) {
                //                bLogin = true;
                Log.e("onLoginSuccess", "登录成功: " + userId);
                //                DlgMgr.showToast(BaseActivity.this, getString(R.string.str_login_success));
            }

            // 登录失败事件
            @Override
            public void onLoginFailed(String userId, String module, int errCode, String errMsg) {
                //                DlgMgr.showMsg(BaseActivity.this, "登录失败: " + module + "|" + errCode + "|" + errMsg);
                Log.e("onLoginFailed", "登录失败: " + module + "|" + errCode + "|" + errMsg);
            }

            // 帐号被踢
            @Override
            public void onForceOffline(String userId, String module, int errCode, String errMsg) {
                //                bLogin = false;
                Log.e("onForceOffline", "登录失败: " + module + "|" + errCode + "|" + errMsg);
                //                DlgMgr.showMsg(BaseActivity.this, "帐号被踢下线: " + module + "|" + errCode + "|" + errMsg);
            }
        });

        // 登录SDK
        ILiveLoginManager.getInstance().iLiveLogin(useId, userSig, null);
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public boolean hasLower(String json) {
        if (json == null || "".equals(json)) {
            return false;
        }
        if ((json.contains("[") && json.contains("]"))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 读取配置文件
     */
    public void loadConfigData() {
        try {
            ConfigInfo.getInstance().loadConfig(this, R.raw.config);
        } catch (Exception e) {
            DlgMgr.showMsg(this, "读取配置文件失败，请在【控制台】->【快速上手】中生成配置内容复制到config.json文件");
        }
    }

    /**
     * 动态权限申请
     */
    public boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), REQ_PERMISSION_CODE);
                return false;
            }
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_PERMISSION_CODE:
                for (int ret : grantResults) {
                    if (PackageManager.PERMISSION_GRANTED != ret) {
                        DlgMgr.showMsg(this, "用户没有允许需要的权限，使用可能会受到限制！");
                    }
                }
                break;
            default:
                break;
        }
    }
}
